import {
  reqAddressAdd,
  reqAddressInfo,
  reqAddressUpload,
} from "../../../../../api/address";
import QQMapWX from "../../../../../libs/qqmap-wx-jssdk";
import Schema from "async-validator"; // 对参数进行校验
Page({
  // 页面的初始数据
  data: {
    id: "",
    name: "", // 收货人
    phone: "", // 手机号码
    provinceName: "", // 省
    provinceCode: "", // 省编码
    cityName: "", // 市
    cityCode: "", // 市编码
    districtName: "", // 区
    districtCode: "", // 区编码
    address: "", // 详细地址
    fullAddress: "", // 完整地址
    isDefault: false,
    qqmapwx: "",
  },

  // 保存收货地址
  async saveAddrssForm() {
    const { provinceName, cityName, districtName, address, isDefault } =
      this.data;
    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0,
    };
    // const { valid } = await this.validatorAddress(params);
    // if (!valid) return;
    if (!this.data.name) {
      wx.showToast({ title: "请输入收货人姓名", icon: "none" });
      return;
    }
    if (!this.data.phone) {
      wx.showToast({ title: "请输入收货人手机号", icon: "none" });
      return;
    }
    if (!this.data.provinceName) {
      wx.showToast({ title: "请输入收货人所在区", icon: "none" });
      return;
    }
    if (!this.data.address) {
      wx.showToast({ title: "请输入详细地址", icon: "none" });
      return;
    }

    const res = this.data.id
      ? await reqAddressUpload(params)
      : await reqAddressAdd(params);

    if (res.data.code === 200) {
      wx.navigateBack({
        success: () => {
          wx.showToast({
            title: this.data.id ? "更新收获地址成功!" : "新增地址成功",
            icon: "none",
          });
        },
      });
    }
  },

  // 验证
  validatorAddress(params) {
    // 验证收货人，是否只包含大小写字母，数字和中文字符
    const nameRegExp = "^[a-zA-Z\\d[u4e00-\\u9fa5]+$";

    // 验证手机号，是否符合中国大陆手机号的格式
    const phoneRegExp =
      "^1(?:3\\d|4[4-9]|5[0-35-9]16[67]17[0-8]|8\\d|9\\d)\\d{8}$";

    // 创建验证规则
    const rules = {
      name: [
        {
          require: true,
          message: "请输入收货人姓名",
        },
        { pattern: nameRegExp, message: "收货人姓名不合法" },
      ],
      phone: [
        {
          require: true,
          message: "请输入收货人手机号",
        },
        { pattern: phoneRegExp, message: "收货人手机号不合法" },
      ],
      provinceName: [{ require: true, message: "请输入收货人所在区" }],
      address: [{ require: true, message: "请输入详细地址" }],
    };

    const validator = new Schema(rules);
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        console.log("error=>", errors);
        if (errors) {
          // 如果验证失败，需要给用户进行提示
          wx.showToast({ title: errors[0].message });
          resolve({ valid: false });
        } else {
          resolve({ valid: true });
        }
      });
    });
  },

  // 省市区选择
  onAddressChange(event) {
    console.log("地区", event);
    const [provinceName, cityName, districtName] = event.detail.value;
    const [provinceCode, cityCode, districtCode] = event.detail.code;
    this.setData({
      provinceName: provinceName,
      cityName: cityName,
      districtName: districtName,
      provinceCode: provinceCode,
      cityCode: cityCode,
      districtCode: districtCode,
    });
  },

  // 获取用户地理位置信息
  async onLocation() {
    // 获取当前的地理位置（精度，纬度，高度）
    // const res = await wx.getLocation();

    // 纬度，经度，搜索名字
    const { latitude, longitude, name } = await wx.chooseLocation();
    // console.log("获取用户地理位置=》", res);

    // 逆地址解析
    this.qqmapwx.reverseGeocoder({
      location: {
        latitude,
        longitude,
      },
      success: (res) => {
        console.log("逆向地址解析=》", res);
        // 行政区划代码,省，市，区
        const { adcode, province, city, district } = res.result.ad_info;
        // 街道，门牌
        const { street, street_number } = res.result.address_component;
        // 完整地址
        const { standard_address } = res.result.formatted_addresses;
        this.setData({
          provinceName: province,
          provinceCode: adcode.replace(adcode.substring(2, 6), "00"),
          cityName: city,
          cityCode: adcode.replace(adcode.substring(4, 6), "00"),
          districtName: district,
          districtCode: district && adcode,
          address: street + street_number + name,
          fullAddress: standard_address + name,
        });
      },
    });
  },

  async showAddressInfo(id) {
    if (!id) return;
    this.data.id = id;
    // 动态设置当前页的标题
    wx.setNavigationBarTitle({
      title: "更新收货地址",
    });
    const { data } = await reqAddressInfo(id);

    const {
      name,
      phone,
      provinceName,
      provinceCode,
      cityName,
      cityCode,
      districtName,
      districtCode,
      address,
      fullAddress,
      isDefault,
    } = data.data;
    console.log("收货地址详情=》", data);
    if (data.code === 200) {
      this.setData({
        name: name,
        phone: phone,
        provinceName: provinceName,
        provinceCode: provinceCode,
        cityName: cityName,
        cityCode: cityCode,
        districtName: districtName,
        districtCode: districtCode,
        address: address,
        fullAddress: fullAddress,
        isDefault: isDefault,
      });
    }
  },

  onLoad(options) {
    console.log("options=>", options);
    // 实例化API核心类
    this.qqmapwx = new QQMapWX({
      key: "7TMBZ-P3RWV-E4JPM-57VUS-2N7K7-FHBQJ",
    });

    this.showAddressInfo(options.id);
  },
});
